package com.example.et.controller;

import com.example.et.entity.Result;
import com.example.et.entity.Worker;
import com.example.et.service.WorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/workers")
public class WorkerController {

    @Autowired
    private WorkerService workerService;

    @GetMapping("/")
    public Result getAllWorkers() {
        List<Worker> workers = workerService.list();
        return Result.success(workers);
    }

    @GetMapping("/{id}")
    public Result getWorkerById(@PathVariable Long id) {
        Worker worker = workerService.getById(id);
        return Result.success(worker);
    }

    @PostMapping("/")
    public Result createWorker(@RequestBody Worker worker) {
        boolean saved = workerService.save(worker);
        if (saved) {
            return Result.success(worker);
        } else {
            return Result.error("Failed to create worker");
        }
    }

    @PutMapping("/{id}")
    public Result updateWorker(@PathVariable int id, @RequestBody Worker worker) {
        worker.setId(id);
        boolean updated = workerService.updateById(worker);
        if (updated) {
            return Result.success(worker);
        } else {
            return Result.error("Failed to update worker");
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteWorker(@PathVariable Long id) {
        boolean deleted = workerService.removeById(id);
        if (deleted) {
            return Result.success("Worker deleted successfully");
        } else {
            return Result.error("Failed to delete worker");
        }
    }
}